package cn.wenhe9.gulimall.product.service.impl;

import cn.wenhe9.gulimall.product.service.CategoryBrandRelationService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.wenhe9.gulimall.product.dao.CategoryDao;
import cn.wenhe9.gulimall.product.entity.CategoryEntity;
import cn.wenhe9.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Resource
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public IPage<CategoryEntity> queryPage(Map<String, Object> params) {
        Long currnet = (Long) params.get("page");
        Long limit = (Long) params.get("limit");
        IPage<CategoryEntity> page = this.page(
                new Page<CategoryEntity>(currnet, limit),
                new QueryWrapper<CategoryEntity>()
        );
        return page;
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //查询所有分类
        List<CategoryEntity> categoryList = this.list();

        List<CategoryEntity> level1Menus = categoryList.stream().filter(pmsCategory ->
                pmsCategory.getParentCid() == 0
        ).map(menu -> {
            menu.setChildren(getChildren(menu, categoryList));
            return menu;
        }).sorted(Comparator.comparingInt(menu -> Optional.ofNullable(menu.getSort()).orElse(0))).collect(Collectors.toList());
        //组装成父子的树形结构
        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> idList) {
        //TODO 1.检查当前删除的菜单，是否被别的地方引用
        baseMapper.deleteBatchIds(idList);
    }

    @Transactional
    @Override
    public void updateDetail(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all){
        List<CategoryEntity> categoryList = all.stream().filter(category -> {
            return category.getParentCid().equals(root.getCatId());
        }).map(category -> {
            category.setChildren(getChildren(category, all));
            return category;
        }).sorted(Comparator.comparingInt(menu -> Optional.ofNullable(menu.getSort()).orElse(0))).collect(Collectors.toList());
        if (categoryList.size() > 0){
            return categoryList;
        }
        return null;
    }

}